package artid.com.arttogo.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import org.xutils.DbManager;
import org.xutils.db.Selector;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import artid.com.arttogo.R;
import artid.com.arttogo.app.ArtToGoApp;
import artid.com.arttogo.bean.CatalogueBean;
import artid.com.arttogo.task.CallbackSky;
import artid.com.arttogo.utils.BitmapUtil;
import artid.com.arttogo.utils.DownloadUtil;
import artid.com.arttogo.utils.MyBitmapImageViewTarget;

public class MyCatalogueActivity extends Activity {
    private Context mContext;
    private GridView myCatalogueGrid;
    private List<CatalogueBean> list;
    private ImageView back;
    private OrganizationAdapter organizationAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mycatalogue_list);
        mContext = this;
        myCatalogueGrid = (GridView) findViewById(R.id.grid_mycatalogue);
        initData();
    }

    private void initData() {
        // TODO Auto-generated method stub
        try {
            DbManager db = x.getDb(((ArtToGoApp) ArtToGoApp.getActivity().getApplication())
                    .getDaoConfig());
            Selector<CatalogueBean> selector = db.selector(CatalogueBean.class);
            // 如果要使用条件查询的话可以使用
            // Selector<user> selector =
            // db.selector(User.class).where("id","=",id).and("age",">",10);
            list = selector.findAll();
            // System.out.println("list=" + list.toString());
        } catch (DbException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        back = (ImageView) findViewById(R.id.back_btn);
        back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                finish();

            }
        });
        if (list != null) {
            organizationAdapter = new OrganizationAdapter(list);
            myCatalogueGrid.setAdapter(organizationAdapter);
            DownloadUtil.getInstance().setMyCallbackSky(new CallbackSky() {

                @Override
                public void callBack() {
                    // TODO Auto-generated method stub
                    if (organizationAdapter != null)
                        organizationAdapter.notifyDataSetChanged();
                }
            });
        }
    }

    /**
     * 我的图录适配器
     *
     * @author XiongBin
     */
    class OrganizationAdapter extends BaseAdapter {
        private List<CatalogueBean> list;

        public OrganizationAdapter(List<CatalogueBean> list) {
            // TODO Auto-generated constructor stub
            this.list = list;
        }

        void refreshAdapter(List<CatalogueBean> list) {
            // TODO Auto-generated constructor stub
            this.list = list;
            notifyDataSetChanged();
        }

        @Override
        public View getView(final int index, View convertView, ViewGroup arg2) {
            // TODO Auto-generated method stub
            if (convertView == null) {
                convertView = View.inflate(getApplicationContext(),
                        R.layout.item_mycatalogue, null);
                new ViewHolder(convertView);
            }
            ViewHolder holder = (ViewHolder) convertView.getTag();
            final CatalogueBean coi = list.get(index);
            System.out.println(coi.toString());
            if (coi != null) {
                holder.title.setText(coi.getTitle());
                Glide.with(mContext).load(coi.getImgurl()).asBitmap()
                        .centerCrop().placeholder(R.drawable.tu_bg)
                        .error(R.drawable.tu_bg)
                        .into(new MyBitmapImageViewTarget(holder.logo));
                try {
                    if (fileIsExists(coi.getLocalurl() + ".tmp")) {
                        int size = Integer.valueOf(coi.getSize());
                        int speedProgress = (int) (getFileSize(new File(
                                coi.getLocalurl() + ".tmp")) * 100 / size);
                        holder.progressContent.setText(speedProgress + "%");
                    } else {
                        holder.progressContent.setText("0%");
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (fileIsExists(coi.getLocalurl())) {
                    holder.rel.setVisibility(View.GONE);
                } else {
                    holder.rel.setVisibility(View.VISIBLE);
                    String path = DownloadUtil.getInstance().getPath();
                    if (TextUtils.isEmpty(path)) {
                        holder.load.setVisibility(View.VISIBLE);
                        holder.load.setImageResource(R.drawable.tl_ico_down);

                    } else {
                        if (path.equals(coi.getLocalurl().trim())) {
                            DownloadUtil.getInstance().setTextView(
                                    holder.progressContent);
                            holder.load.setVisibility(View.VISIBLE);
                            holder.load
                                    .setImageResource(R.drawable.tl_ico_stop);
                        } else {
                            if (coi.getProgress().equals("0")) {
                                holder.load.setVisibility(View.GONE);
                            } else {
                                holder.load.setVisibility(View.VISIBLE);
                                // holder.progressContent.setText(coi
                                // .getProgress() + "%");
                            }
                        }
                    }

                }
                holder.load.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        String path = DownloadUtil.getInstance().getPath();
                        if (TextUtils.isEmpty(path)) {
                            DownloadUtil.getInstance().httpDownLoad(
                                    coi.getLocalurl(), coi.getZipurl(), false);
                            notifyDataSetChanged();
                        } else {
                            DownloadUtil.getInstance().cancelableCancel();
                            notifyDataSetChanged();
                        }
                    }
                });
                holder.logo.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        String lurl = coi.getLocalurl();

                        if (fileIsExists(lurl)) {
                            String mark = lurl.substring(0, lurl.length() - 4);
                            String url = mark + DownloadUtil.forderName;
                            File file = new File(mark);
                            Intent in = new Intent(mContext,
                                    CatalogueDetailsActivity.class);
                            if (!file.exists()) {// 解压并跳页面
                                try {
                                    unZip(mContext, lurl, DownloadUtil.baseUrl
                                            + coi.getName(), true);
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                            in.putExtra("url", url);
                            in.putExtra("type", DownloadUtil.NOTE_OFFLINE);
                            in.putExtra("imageurl", coi.getImgurl());
                            in.putExtra("content", coi.getInfo());
                            in.putExtra("surl", coi.getHtmlurl());
                            startActivity(in);
                        }
                    }
                });
                // Glide.with(mContext).load(coi.getLogo())
                // .placeholder(R.drawable.tu_bg).error(R.drawable.tu_bg)
                // .into(holder.logo);
            }
            return convertView;
        }

        class ViewHolder {
            TextView title, progressContent, info;
            ImageView logo, load;
            RelativeLayout rel;

            public ViewHolder(View view) {
                title = (TextView) view.findViewById(R.id.tv_title);
                logo = (ImageView) view.findViewById(R.id.iv_logo);
                load = (ImageView) view.findViewById(R.id.iv_load);
                progressContent = (TextView) view.findViewById(R.id.tv_load);
                info = (TextView) view.findViewById(R.id.tv_load_info);
                rel = (RelativeLayout) view.findViewById(R.id.rel_load);
                view.setTag(this);
            }
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public CatalogueBean getItem(int arg0) {
            // TODO Auto-generated method stub
            return list.get(arg0);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }
    }

    ;

    /**
     * 获取指定文件大小
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            file.createNewFile();
            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

    public boolean fileIsExists(String path) {
        try {
            File f = new File(path);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }
        return true;
    }

    /**
     * 解压assets的zip压缩文件到指定目录
     *
     * @param context         上下文对象
     * @param assetName       压缩文件名
     * @param outputDirectory 输出目录
     * @param isReWrite       是否覆盖
     * @throws IOException
     */
    public static void unZip(Context context, String urlName,
                             String outputDirectory, boolean isReWrite) throws IOException {
        // 创建解压目标目录
        File file = new File(outputDirectory);
        // 如果目标目录不存在，则创建
        if (!file.exists()) {
            file.mkdirs();
        }
        // 打开压缩文件
        ZipInputStream zipInputStream = new ZipInputStream(
                new BufferedInputStream(new FileInputStream(urlName)));
        // 读取一个进入点
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        // 使用1Mbuffer
        byte[] buffer = new byte[1024 * 1024];
        // 解压时字节计数
        int count = 0;
        // 如果进入点为空说明已经遍历完所有压缩包中文件和目录
        while (zipEntry != null) {
            // 如果是一个目录
            if (zipEntry.isDirectory()) {
                file = new File(outputDirectory + File.separator
                        + zipEntry.getName());
                // 文件需要覆盖或者是文件不存在
                if (isReWrite || !file.exists()) {
                    file.mkdir();
                }
            } else {
                // 如果是文件
                file = new File(outputDirectory + File.separator
                        + zipEntry.getName());
                // 文件需要覆盖或者文件不存在，则解压文件
                if (isReWrite || !file.exists()) {
                    file.createNewFile();
                    FileOutputStream fileOutputStream = new FileOutputStream(
                            file);
                    while ((count = zipInputStream.read(buffer)) > 0) {
                        fileOutputStream.write(buffer, 0, count);
                    }
                    fileOutputStream.close();
                }

            }
            // 定位到下一个文件入口
            zipEntry = zipInputStream.getNextEntry();
        }
        zipInputStream.close();
    }
}
